package com.liao.seckill.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liao.seckill.result.Result;
import com.liao.seckill.result.ResultCode;
import com.liao.seckill.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthHandlerInterceptor implements HandlerInterceptor {

    private static final String[] passUrl = {"/auth/captcha","/auth/login"};

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI());
        for (String s : request.getParameterMap().keySet()) {
            System.out.println(request.getParameter(s));
        }
        if (checkUrl(request.getRequestURI())) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null){
            Result<Object> result = new Result<>(ResultCode.TOKEN_ERROR);
            writeToResponse(response,result);
            return false;
        }
        Claims claims = null;
        try {
            claims = JwtTokenUtil.getInfoFromToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            Result<Object> result = new Result<>(ResultCode.TOKEN_ERROR);
            writeToResponse(response,result);
            return false;
        }
        request.setAttribute("userId",claims.get("id"));
        return true;
    }

    private boolean checkUrl(String url){
        for (String s : passUrl) {
            if (s.equals(url)){
                return true;
            }
        }
        return false;
    }

    private void writeToResponse(HttpServletResponse response,Result<Object> result){
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
